<template>
  <view class="register-container">
    <view class="register-header">
      <view class="register-logo">
        <image src="/static/logo.png" mode="aspectFit"></image>
        <text class="logo-text">MoeConnect</text>
      </view>
      <text class="register-title">创建账户</text>
      <text class="register-subtitle">加入我们，开启精彩旅程</text>
      
      <!-- 服务器状态显示 -->
      <view class="connection-status">
        <view :class="['status-indicator', serverStatus]"></view>
        <text>{{ statusText }}</text>
      </view>
    </view>
    
    <view class="form-content">
      <view class="form-group">
        <text class="form-label">昵称</text>
        <view class="input-wrapper">
          <text class="input-icon">👤</text>
          <input 
            id="name" 
            v-model="formData.name" 
            type="text" 
            class="form-input" 
            placeholder="请输入昵称" 
          />
        </view>
      </view>

      <view class="form-group">
        <text class="form-label">邮箱</text>
        <view class="input-wrapper">
          <text class="input-icon">✉️</text>
          <input 
            id="register-email" 
            v-model="formData.email" 
            type="text" 
            class="form-input" 
            placeholder="请输入邮箱" 
          />
        </view>
      </view>

      <view class="form-group">
        <text class="form-label">密码</text>
        <view class="input-wrapper">
          <text class="input-icon">🔒</text>
          <input 
            id="register-password"
            v-model="formData.password" 
            :type="showPassword ? 'text' : 'password'" 
            class="form-input" 
            placeholder="请输入密码" 
          />
          <text
            class="toggle-password"
            @click="showPassword = !showPassword"
          >{{ showPassword ? '👁️' : '🙈' }}</text>
        </view>
      </view>

      <view class="form-group">
        <text class="form-label">确认密码</text>
        <view class="input-wrapper">
          <text class="input-icon">🔒</text>
          <input 
            id="confirm-password"
            v-model="formData.confirmPassword" 
            :type="showConfirmPassword ? 'text' : 'password'" 
            class="form-input" 
            placeholder="请再次输入密码" 
          />
          <text
            class="toggle-password"
            @click="showConfirmPassword = !showConfirmPassword"
          >{{ showConfirmPassword ? '👁️' : '🙈' }}</text>
        </view>
      </view>

      <button type="button" class="btn-primary auth-btn" :disabled="isLoading" @click="handleRegister">
        <template v-if="isLoading">
          <text class="loading-icon">⏳</text>
          <text>注册中...</text>
        </template>
        <template v-else>注册</template>
      </button>
      
      <view v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </view>
      
      <view v-if="successMessage" class="success-message">
        {{ successMessage }}
      </view>
      
      <!-- 登录链接 -->
      <view class="login-link">
        <text class="login-text">已有账户？</text>
        <text class="login-btn" @click="navigateToLogin">立即登录</text>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '../../../utils/api-service.js'
import appStateManager from '../../../utils/app-state-manager.js'

export default {
  data() {
    return {
      formData: {
        name: '',
        email: '',
        password: '',
        confirmPassword: ''
      },
      isLoading: false,
      errorMessage: '',
      successMessage: '',
      serverStatus: 'offline',
      statusText: '正在检查服务器状态...',
      showPassword: false,
      showConfirmPassword: false
    }
  },
  
  onLoad() {
    appStateManager.subscribe('server', (serverState) => {
      this.isServerOnline = serverState.isOnline
    })
  },
  
  methods: {
    async handleRegister() {
      // 验证表单
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入用户名',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.email) {
        uni.showToast({
          title: '请输入邮箱地址',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.password) {
        uni.showToast({
          title: '请输入密码',
          icon: 'none'
        })
        return
      }
      
      if (!this.formData.confirmPassword) {
        uni.showToast({
          title: '请确认密码',
          icon: 'none'
        })
        return
      }
      
      // 验证密码是否一致
      if (this.formData.password !== this.formData.confirmPassword) {
        uni.showToast({
          title: '两次输入的密码不一致',
          icon: 'none'
        })
        return
      }
      
      // 验证密码长度
      if (this.formData.password.length < 6) {
        uni.showToast({
          title: '密码长度至少6位',
          icon: 'none'
        })
        return
      }
      
      this.isLoading = true
      this.errorMessage = ''
      this.successMessage = ''
      
      try {
        // 尝试使用API服务注册
        const response = await apiService.register({
          name: this.formData.name,
          email: this.formData.email,
          password: this.formData.password
        })
        
        console.log('注册响应:', response)
        console.log('响应类型:', typeof response)
        console.log('响应内容:', JSON.stringify(response))
        
        // 检查注册是否成功
        if (response.code === 'SUCCESS' || response.message?.includes('注册成功')) {
          const serverStatus = appStateManager.getState("server")
          const statusText = serverStatus.isOnline ? 
            '（已保存到服务器）' : 
            '（本地模式）'
          
          this.successMessage = `注册成功！${statusText} 正在跳转到登录页面...`
          
          // 如果有用户数据，同步到本地存储
          if (response.data && response.data.user) {
            this.syncUserToLocal(response.data.user)
          }
          
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          })
          
          // 延迟跳转到登录页面，并传递注册的邮箱
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/auth/login/login?email=${this.formData.email}`
            })
          }, 1500)
        } else {
          // 如果服务器在线但没有返回成功信息，说明注册失败
          const serverStatus = appStateManager.getState("server")
          if (serverStatus.isOnline) {
            throw new Error('服务器注册失败，请检查邮箱是否已被注册')
          }
        }
        
      } catch (error) {
        console.error('注册失败:', error)
        
        // 解析服务器返回的详细错误信息
        let errorTitle = '注册失败'
        let errorMessage = '请重试'
        
        if (error.message) {
          // 如果是服务器返回的结构化错误信息
          try {
            const errorData = JSON.parse(error.message)
            if (errorData.code && errorData.message) {
              errorTitle = errorData.message
              errorMessage = errorData.data?.details || errorData.message
              
              // 如果有建议信息，也显示出来
              if (errorData.data?.suggestion) {
                errorMessage += '\n\n建议：' + errorData.data.suggestion
              }
            }
          } catch (parseError) {
            // 如果不是JSON格式，直接使用错误信息
            errorTitle = '注册失败'
            errorMessage = error.message
          }
        }
        
        this.errorMessage = errorMessage
        uni.showModal({
          title: errorTitle,
          content: errorMessage,
          showCancel: false,
          confirmText: '知道了'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 同步用户数据到本地存储
    syncUserToLocal(user) {
      console.log('同步用户数据到本地:', user)
      
      const users = uni.getStorageSync('users')
      let userList = []
      
      if (users) {
        userList = JSON.parse(users)
      }
      
      const existingIndex = userList.findIndex(u => u.id === user.id || u.email === user.email)
      
      if (existingIndex !== -1) {
        // 保留现有用户的密码（如果新用户数据没有密码字段）
        const existingPassword = userList[existingIndex].password
        userList[existingIndex] = { ...userList[existingIndex], ...user }
        // 如果新用户数据没有密码，保留原有的密码
        if (!user.password && existingPassword) {
          userList[existingIndex].password = existingPassword
        }
      } else {
        // 如果是新用户，确保包含密码
        if (!user.password && this.formData.password) {
          user.password = this.formData.password
        }
        userList.push(user)
      }
      
      console.log('保存到本地的用户列表:', userList)
      uni.setStorageSync('users', JSON.stringify(userList))
    },
    
    
    navigateToLogin() {
      uni.navigateTo({
        url: '/pages/auth/login/login'
      })
    },
    
    navigateToIndex() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    }
    
  }
}
</script>

<style scoped>
/* CSS变量定义 - 作为后备方案，确保在所有平台都能正常工作 */
:root {
  --primary-color: #7B68EE;
  --primary-hover: #6A5ACD;
  --primary-light: #9B88FF;
  --secondary-color: #48BB78;
  --danger-color: #F56565;
  --warning-color: #ED8936;
  --text-primary: #2D3748;
  --text-secondary: #4A5568;
  --text-light: #718096;
  --bg-primary: #FFFFFF;
  --bg-secondary: #F7FAFC;
  --bg-card: #FFFFFF;
  --border-color: #E2E8F0;
  --border-radius-base: 12px;
  --border-radius-lg: 16px;
  --shadow-light: 0 2px 8px rgba(0, 0, 0, 0.1);
  --shadow-medium: 0 8px 25px rgba(0, 0, 0, 0.15);
  --shadow-heavy: 0 20px 40px rgba(0, 0, 0, 0.2);
  --transition-base: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  --transition-fast: all 0.2s ease;
}

/* 基础布局 */
.register-container {
  height: 100vh;
  max-height: 100vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  animation: fadeInUp 0.8s ease-out;
  box-sizing: border-box;
}

/* 背景装饰 */
.register-container::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: 
    radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(255, 255, 255, 0.05) 0%, transparent 50%);
  animation: float 20s ease-in-out infinite;
  pointer-events: none;
  z-index: 0;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  33% { transform: translateY(-20px) rotate(1deg); }
  66% { transform: translateY(10px) rotate(-1deg); }
}

/* 头部区域 */
.register-header {
  text-align: center;
  margin-bottom: 15px;
  margin-top: 10px;
  animation: fadeIn 0.6s ease-out 0.2s both;
  position: relative;
  z-index: 1;
  flex-shrink: 0;
}

.register-logo {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12px;
}

.register-logo image {
  width: 55px;
  height: 55px;
  margin-right: 10px;
  animation: logoBounce 0.8s ease-out 0.4s both;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.logo-text {
  font-size: 22px;
  font-weight: 700;
  background: linear-gradient(90deg, #ffffff, #f0f0f0);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 兼容性处理：如果background-clip不支持，使用白色作为后备 */
  @supports not (background-clip: text) {
    color: #ffffff;
    background: none;
  }
}

.register-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.register-subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.connection-status {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20rpx;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-indicator.online {
  background-color: #4CAF50;
}

.status-indicator.offline {
  background-color: #f44336;
}

/* 表单内容容器 */
.form-content {
  width: 100%;
  max-width: 380px;
  background: var(--bg-card);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-heavy);
  padding: 24px;
  margin-bottom: 20px;
  transition: var(--transition-base);
  animation: slideInUp 0.8s ease-out 0.4s both;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
}

.form-content:hover {
  transform: translateY(-5px);
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
}

/* 表单组 */
.form-group {
  margin-bottom: 18px;
  animation: fadeInUp 0.6s ease-out 0.6s both;
  position: relative;
  z-index: 2;
}

.form-group:nth-child(2) {
  animation-delay: 0.7s;
}

.form-group:nth-child(3) {
  animation-delay: 0.8s;
}

.form-group:nth-child(4) {
  animation-delay: 0.9s;
}

.form-group:nth-child(5) {
  animation-delay: 1s;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: var(--text-primary);
  transition: var(--transition-fast);
}

.form-group:focus-within .form-label {
  color: var(--primary-color);
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #E2E8F0;
  border-radius: 12px;
  background: #F7FAFC;
  transition: all 0.3s ease;
}

.input-icon {
  padding: 0 16px;
  font-size: 16px;
  color: #718096;
  user-select: none;
}

.form-input {
  flex: 1;
  padding: 16px 0;
  border: none;
  background: transparent;
  font-size: 16px;
  color: #2D3748;
  outline: none;
}

.form-input:focus {
  outline: none;
}

.input-wrapper:focus-within {
  border-color: #2D3748;
  background: #ffffff;
  box-shadow: 0 0 0 3px rgba(45, 55, 72, 0.1);
}

.form-input::placeholder {
  color: #A0AEC0;
}

.toggle-password {
  padding: 0 16px;
  font-size: 16px;
  color: #718096;
  cursor: pointer;
  user-select: none;
}

.toggle-password:hover {
  color: var(--primary-color);
}

/* 主要按钮 */
.btn-primary {
  width: 100%;
  padding: 16px 24px;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white !important;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
  margin-bottom: 16px;
  animation: fadeInUp 0.6s ease-out 1.3s both;
  display: block;
  min-height: 48px;
  line-height: 1.2;
  text-align: center;
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.btn-primary:hover::before {
  left: 100%;
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(76, 175, 80, 0.4);
  background: linear-gradient(135deg, #66BB6A 0%, #4CAF50 100%);
}

.btn-primary:active {
  transform: translateY(0);
}

.btn-primary:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.auth-btn {
  animation: fadeInUp 0.6s ease-out 1.3s both;
}

.loading-icon {
  margin-right: 8px;
  animation: spin 1s linear infinite;
}

/* 按钮文本样式 */
.btn-primary text {
  color: white !important;
  font-size: 16px;
  font-weight: 600;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 错误消息 */
.error-message {
  color: var(--danger-color);
  font-size: 12px;
  margin-top: 5px;
  display: block;
  animation: shake 0.5s ease-in-out;
  text-align: center;
  margin-bottom: 20px;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 成功消息 */
.success-message {
  color: var(--secondary-color);
  font-size: 14px;
  text-align: center;
  padding: 12px;
  background: rgba(72, 187, 120, 0.1);
  border-radius: var(--border-radius-base);
  margin-bottom: 16px;
  animation: fadeInUp 0.6s ease-out;
}

/* 底部链接 - 在卡片内部 */
.login-link {
  text-align: center;
  animation: fadeInUp 0.6s ease-out 1.4s both;
  position: relative;
  z-index: 2;
  margin-top: 20px;
  padding: 0;
}

.login-text {
  color: #ffffff;
  font-size: 14px;
  margin-right: 8px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.login-btn {
  color: #7089fa;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: underline;
  text-decoration-color: #7089fa;
  font-size: 14px;
  text-shadow: 0 0 8px rgba(112, 137, 250, 0.5);
  position: relative;
}

.login-btn:hover {
  color: #ffffff;
  text-decoration-color: #ffffff;
  transform: scale(1.05);
  text-shadow: 0 0 15px rgba(255, 255, 255, 0.8), 0 0 25px rgba(112, 137, 250, 0.6);
}

/* 动画定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(50px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes logoBounce {
  0% {
    opacity: 0;
    transform: scale(0.5) rotate(-180deg);
  }
  50% {
    transform: scale(1.1) rotate(0deg);
  }
  100% {
    opacity: 1;
    transform: scale(1) rotate(0deg);
  }
}
</style>
